package com.common.base.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.CallSuper;
import androidx.annotation.ColorInt;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.ContextCompat;
import com.common.R;
import com.common.bean.InfoResult;
import com.common.bean.MsgBean;
import com.common.theme.Theme;
import com.common.theme.ThemeHelper;
import com.common.theme.Themed;
import com.common.theme.UiElementInizializer;
import com.common.theme.ViewUtil;
import com.common.ui.alerter.Alerter;
import com.common.ui.alerter.OnHideAlertListener;
import com.common.ui.alerter.OnShowAlertListener;
import com.common.ui.barlibrary.ImmersionBar;
import com.common.ui.barlibrary.OSUtils;
import com.common.ui.swipebacklayout.lib.SwipeBackLayout;
import com.common.ui.swipebacklayout.lib.app.SwipeBackActivity;
import com.common.utils.StatusBarUtil;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.typeface.IIcon;
import com.orhanobut.hawk.Hawk;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.ButterKnife;

public abstract class BaseThemeActivity extends SwipeBackActivity implements UiElementInizializer {

    private ActivityManager activityManager = ActivityManager.getActivityManager();
    private EventBus eventBus;
    private Toast toast = null;
    private SwipeBackLayout swipeBackLayout;
    private InputMethodManager inputMethodManager;
    private ThemeHelper themeHelper;
    private boolean coloredNavBar;//虚拟导航栏
    private boolean obscuredStatusBar;//是否全透明
    private boolean applyThemeSingleImgAct;
    private boolean customIconColor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(null != activityManager) {
            activityManager.putActivity(this);
        }
        //初始化沉浸式
        initImmersionBar();
        //把设置布局文件的操作交给继承的子类
        setContentView(getLayoutResId());
        themeHelper = ThemeHelper.getInstance(getApplicationContext());
        ButterKnife.bind(this);
        setScreenVertical(this);
        initSwipeBack();
        eventBus = EventBus.getDefault();
        eventBus.register(this);
        init();
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 非必加
        // 如果你的app可以横竖屏切换，适配了华为emui3系列系统手机，并且navigationBarWithEMUI3Enable为true，
        // 请在onResume方法里添加这句代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、华为emui3系列系统手机；3、navigationBarWithEMUI3Enable为true）
        // 否则请忽略
        if (OSUtils.isEMUI3_x() && isImmersionBarEnabled()) {
            ImmersionBar.with(this).init();
        }
        updateTheme();
        updateUiElements();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isImmersionBarEnabled()) {
            // 非必加
            // 如果你的app可以横竖屏切换，适配了4.4或者华为emui3.1系统手机，并且navigationBarWithKitkatEnable为true，
            // 请务必在onConfigurationChanged方法里添加如下代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、android4.4或者华为emui3.1系统手机；3、navigationBarWithKitkatEnable为true）
            // 否则请忽略
            ImmersionBar.with(this).init();
        }
    }

    @Override
    public void finish() {
        super.finish();
        hideSoftKeyBoard();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        inputMethodManager = null;
        if(eventBus!=null){
            eventBus.unregister(this);
        }
        if(null != activityManager) {
            activityManager.removeActivity(this);
        }
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).destroy();
        }
    }

    public void updateTheme(){
        themeHelper.updateTheme();
        coloredNavBar = Hawk.get(getString(R.string.preference_colored_nav_bar), false);
        obscuredStatusBar = Hawk.get(getString(R.string.preference_translucent_status_bar), true);
        applyThemeSingleImgAct = Hawk.get("apply_theme_img_act", true);
        customIconColor = Hawk.get(getString(R.string.preference_custom_icon_color), false);
    }

    @CallSuper
    @Override
    public void updateUiElements() {
        for (View view : ViewUtil.getAllChildren(findViewById(android.R.id.content))) {
            if (view instanceof Themed) ((Themed) view).refreshTheme(getThemeHelper());
        }
    }

    /**
     * 设置Activity的显示方向为横向
     *
     * @param activity
     */
    @SuppressLint("SourceLockedOrientationActivity")
    private void setScreenHorizontal(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /**
     * 设置Activity的显示方向为垂直方向
     *
     * @param activity
     */
    @SuppressLint("SourceLockedOrientationActivity")
    private void setScreenVertical(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    protected void initImmersionBar() {
        if (isImmersionBarEnabled()) {
            //在BaseActivity里初始化
            //ImmersionBar.with(this).init();
            ImmersionBar.with(this).navigationBarColor(R.color.colorPrimary).init();
        }
    }

    private void initSwipeBack(){
        if(isSupportSwipeBackEnabled()){
            // 可以调用该方法，设置是否允许滑动退出
            setSwipeBackEnable(true);
            swipeBackLayout = getSwipeBackLayout();
            // 设置滑动方向，可设置EDGE_LEFT, EDGE_RIGHT, EDGE_ALL, EDGE_BOTTOM
            swipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
            // 滑动退出的效果只能从边界滑动才有效果，如果要扩大touch的范围，可以调用这个方法
            //swipeBackLayout.setEdgeSize(200);
        }else {
            setSwipeBackEnable(false);
        }
    }
    //===================================alerter==========================================
    public void showAlert(String msg){
        Alerter.create(this)
                .setText(msg)
                .disableOutsideTouch()
                .setDuration(700)
                .show();
    }

    private void showAlertDefault() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .disableOutsideTouch()
                .show();
    }

    private void showAlertColoured() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setBackgroundColor(R.color.colorAccent)
                .show();
    }

    private void showAlertWithIcon() {
        Alerter.create(this)
                .setText("Alert text...")
                .setIcon(R.drawable.alerter_ic_face)
                .show();
    }

    private void showAlertTextOnly() {
        Alerter.create(this)
                .setText("Alert text...")
                .show();
    }

    private void showAlertWithOnClick() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setDuration(10000)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(BaseThemeActivity.this, "OnClick Called", Toast.LENGTH_LONG).show();
                    }
                })
                .show();
    }

    private void showAlertVerbose() {
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("The alert scales to accommodate larger bodies of text. " +
                        "The alert scales to accommodate larger bodies of text. " +
                        "The alert scales to accommodate larger bodies of text.")
                .show();
    }

    private void showAlertCallbacks(){
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setDuration(10000)
                .setOnShowListener(new OnShowAlertListener() {
                    @Override
                    public void onShow() {
                        Toast.makeText(BaseThemeActivity.this, "Show Alert", Toast.LENGTH_LONG).show();
                    }
                })
                .setOnHideListener(new OnHideAlertListener() {
                    @Override
                    public void onHide() {
                        Toast.makeText(BaseThemeActivity.this, "Hide Alert", Toast.LENGTH_LONG).show();
                    }
                })
                .show();
    }

    private void showAlertInfiniteDuration() {
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .enableInfiniteDuration(true)
                .show();
    }

    /**
     * 跳转到权限设置界面
     */
    public void goIntentSetting() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerMeg(MsgBean msgBean) {

    }

    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    public int getColor(Context context, int id) {
        return ContextCompat.getColor(context, id);
    }

    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.inputMethodManager == null) {
            this.inputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        }
        if ((localView != null) && (this.inputMethodManager != null)) {
            this.inputMethodManager.hideSoftInputFromWindow(localView.getWindowToken(), 2);
        }
    }
    /**
     * 跳转到某个Activity
     * @param activity
     * @param targetActivity
     */
    public void switchTo(Activity activity, Class<? extends Activity> targetActivity, boolean finish) {
        switchTo(activity, new Intent(activity, targetActivity),finish);
    }

    public void switchTo(Activity activity, Intent intent, boolean finish) {
        activity.startActivity(intent);
        if(finish){
            finish();
        }
        //overridePendingTransition(R.anim.alpha_out, R.anim.alpha_in);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void setStatusBarColor(@ColorInt int color) {
      /*  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final Window window = getWindow();
            if (window != null) {
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(color);
            }
        }*/
        StatusBarUtil.setColor(this, color,0);
    }

    //设置手机底部虚拟导航键颜色
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void setNavBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (isNavigationBarColored()) {
                getWindow().setNavigationBarColor(getPrimaryColor());
            } else {
                getWindow().setNavigationBarColor(ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
            }
        }
    }
    // -------------------- BaseActivity的辅助封装 --------------------- //

    public abstract boolean isImmersionBarEnabled();
    /**
     * 是否支持滑动返回
     *
     * @return
     */
    public abstract boolean isSupportSwipeBackEnabled();

    /**
     * 返回当前Activity布局文件的id
     *
     * @return
     */
    public abstract int getLayoutResId();

    /**
     * 初始化的一些操作
     */
    public abstract void init();

    /**
     * 加载网络数据
     */
    public abstract void loadData();

    /**
     * 网络数据返回成功
     */
    protected abstract void onSuccess(int what, InfoResult t);

    /**
     * 网络数据返回失败
     */
    protected abstract void onFail(int what, InfoResult t);

    public EventBus getEventBus() {
        return eventBus;
    }

    public ThemeHelper getThemeHelper() {
        return themeHelper;
    }

    public void setThemeHelper(ThemeHelper themeHelper) {
        this.themeHelper = themeHelper;
    }

    public boolean isNavigationBarColored() {
        return coloredNavBar;
    }

    public boolean isTranslucentStatusBar() {
        return obscuredStatusBar;
    }

    public boolean themeOnSingleImgAct() {
        return applyThemeSingleImgAct;
    }

    protected boolean isTransparencyZero() {
        return true;
        /* return 255 - (getString(R.string.preference_transparency), 0) == 255;*/
    }

    public int getTransparency() {
        return 0;
        /*return 255 - SP.getInt(getString(org.horaapps.leafpic.R.string.preference_transparency), 0);*/
    }

    public void setBaseTheme(Theme baseTheme) {
        themeHelper.setBaseTheme(baseTheme);
    }

    public void themeSeekBar(SeekBar bar) {
        themeHelper.themeSeekBar(bar);
    }
    public int getPrimaryColor() {
        return themeHelper.getPrimaryColor();
    }

    public int getAccentColor() {
        return themeHelper.getAccentColor();
    }

    public Theme getBaseTheme(){ return  themeHelper.getBaseTheme(); }

    public int getBackgroundColor(){
        return themeHelper.getBackgroundColor();
    }

    protected Drawable getPlaceHolder(){
        return themeHelper.getPlaceHolder();
    }

    protected int getInvertedBackgroundColor(){
        return themeHelper.getInvertedBackgroundColor();
    }

    public int getTextColor(){
        return themeHelper.getTextColor();
    }

    public int getSubTextColor(){
        return themeHelper.getSubTextColor();
    }

    public int getCardBackgroundColor(){
        return themeHelper.getCardBackgroundColor();
    }

    public int getIconColor(){
        return themeHelper.getIconColor();
    }

    protected int getDrawerBackground(){
        return themeHelper.getDrawerBackground();
    }

    public int getDialogStyle(){
        return themeHelper.getDialogStyle();
    }

    protected int getPopupToolbarStyle(){
        return themeHelper.getPopupToolbarStyle();
    }

    protected ArrayAdapter<String> getSpinnerAdapter(ArrayList<String> items) {
        return themeHelper.getSpinnerAdapter(items);
    }

    protected int getDefaultThemeToolbarColor3th(){
        return themeHelper.getDefaultThemeToolbarColor3th();
    }

    public void themeRadioButton(RadioButton radioButton) {
        themeHelper.themeRadioButton(radioButton);
    }

    public void themeCheckBox(CheckBox chk) {
        themeHelper.themeCheckBox(chk);
    }

    protected void themeButton(Button btn) {themeHelper.themeButton(btn);}

    public void setSwitchColor(int color, SwitchCompat... sw){
        for (SwitchCompat switchCompat : sw) {
            themeHelper.setSwitchCompactColor(switchCompat, color);
        }
    }

    public void setTextViewColor(int color, TextView... textViews){
        for (TextView txt: textViews) {
            themeHelper.setTextViewColor(txt, color);
        }
    }

    public IconicsDrawable getToolbarIcon(IIcon icon){
        return themeHelper.getToolbarIcon(icon);
    }
}
